package com.woniuxy.juc;

import com.woniuxy.untis.Sleep;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <P> @Author: ideaAdmin
 * <P> TODO: Class
 * <P> TODO: 等待倒计时计数才能运行
 * <P> Date: 2022/4/12:16:36
 * <P> Description:
 */
@Slf4j(topic = "c.c")
@SuppressWarnings("all")
public class CountDownLatchTest {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService service = Executors.newFixedThreadPool(10);
        CountDownLatch latch = new CountDownLatch(10);
        String[] all = new String[10];
        Random random = new Random();
        for (int i = 0; i < 10; i++) {
            int k = i;
            service.submit(() -> {
                for (int j = 0; j <= 100; j++) {
                    all[k] = j + "%";
                    Sleep.sleep(random.nextInt(100));
                    System.out.print("\r" + Arrays.toString(all));
                }
                latch.countDown();
            });
        }

        latch.await();
        System.out.println("\n游戏开始");
        service.shutdown();
    }

    private static void threadPoolCountDown() throws InterruptedException {
        ExecutorService service = Executors.newFixedThreadPool(4);

        CountDownLatch latch = new CountDownLatch(3);
        service.submit(() -> {
            log.debug("begin");
            Sleep.sleep(1L);
            latch.countDown();

            log.debug("end");
        });

        service.submit(() -> {
            log.debug("begin");
            Sleep.sleep(2L);
            latch.countDown();

            log.debug("end");
        });


        service.submit(() -> {
            log.debug("begin");
            Sleep.sleep(3L);
            latch.countDown();

            log.debug("end");
        });


        log.debug("waiting");
        latch.await();
        log.debug("wait end");
    }

    private static void countDownLatchMthod() throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(3);

        new Thread(() -> {
            log.debug("begin");
            Sleep.sleep(1L);
            latch.countDown();

            log.debug("end");
        }).start();

        new Thread(() -> {
            log.debug("begin");
            Sleep.sleep(1L);
            latch.countDown();

            log.debug("end");
        }).start();

        new Thread(() -> {
            log.debug("begin");
            Sleep.sleep(1L);
            latch.countDown();

            log.debug("end");
        }).start();


        log.debug("waiting");
        latch.await();
        log.debug("wait end");
    }
}
